<?php
/**
 * Created by PhpStorm.
 * User: UEWARE
 * Date: 2019-7-18
 * Time: 10:46:10
 */

namespace App\Http\Controllers\WeChat\Diary\V1\User;

use App\Factory\MiniProgram;
use App\Http\Controllers\WeChat\WeChatController;
use App\Models\UserModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;

class LoginController extends WeChatController
{
    /**
     * 非必须登录
     *
     * @var bool
     */
    protected $requireLogin = false;

    /**
     * 用户登录
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function index(Request $request)
    {
        // 获取当前code值
        $code = $request->input();

        if (empty($code['code'])) {
            return error(100000);
        }

        // 获取信息
        $wechat = MiniProgram::app()->auth->session($code['code']);

        if (array_key_exists("errcode", $wechat)) {
            return error(100000);
        }

        try {
            $user = UserModel::query()->where('openid', $wechat['openid'])->first();

            if (empty($user)) {
                UserModel::query()->create(['openid' => $wechat['openid']]);
            }
        } catch (\Exception $e) {
            return error(100000);
        }

        $result['token'] = Crypt::encrypt($wechat);

        return success($result);
    }
}